package com.example.xgakj.newterminal.ui.activities;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.xgakj.mylibrary.mvp.utils.CommonUtil;
import com.example.xgakj.mylibrary.mvp.utils.DensityUtils;
import com.example.xgakj.mylibrary.mvp.utils.KeyBoardUtils;
import com.example.xgakj.mylibrary.mvp.utils.TimeUtil;
import com.example.xgakj.newterminal.R;
import com.example.xgakj.newterminal.adapter.DataAdapter;
import com.example.xgakj.newterminal.base.BaseActivity;
import com.example.xgakj.newterminal.base.BaseApplication;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.beans.AlarmTable;
import com.example.xgakj.newterminal.ui.framents.AlarmDetailFragment;
import com.example.xgakj.newterminal.utils.NetUtil;
import com.example.xgakj.newterminal.views.ViewWrapper;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.qmuiteam.qmui.util.QMUIViewHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.socks.library.KLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AlarmRecordActivity extends BaseActivity {

    @BindView(R.id.list)
    LRecyclerView mRecyclerView;
    private static final String TAG = "lzx";
    @BindView(R.id.topbar)
    QMUITopBar topbar;
    @BindView(R.id.content)
    FrameLayout content;
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.tv_start)
    TextView tvStart;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    private boolean end;
    private boolean isLogHis;
    /**
     * 已经获取到多少条数据了
     */
    private static int mCurrentCounter = 1;

//    private LRecyclerView mRecyclerView = null;

    private DataAdapter mDataAdapter = null;
    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    ArrayList<AlarmTable> alarmList;
    private String field, param_filter, tableName;
    private ViewWrapper viewWrapper;
    private Button btnShow;
    private boolean isShowingSearch;//搜索框是否显示
    private boolean isShowingDefence;//显示的是否是布撤防页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_record);
        ButterKnife.bind(this);
        initTopbar();
        alarmList = new ArrayList<>();
        field = "id,dateon,custid,partid,jqneirong,jingqingid,fangqu,note,ifok,disposal,clientok,itype";
        int intExtra = getIntent().getIntExtra(Parameters.TYPE, 6);
        if (intExtra == Parameters.TYPE_ALARM) {
            param_filter = "custid='" + BaseApplication.usrID + "'" + " and JQNeiRong not like '%" + "布防" + "%'" + " and JQNeiRong not like '%" + "撤防" + "%'";
        } else if (intExtra == Parameters.TYPE_DEFENCE) {
            isShowingDefence = true;
            param_filter = "custid='" + BaseApplication.usrID + "'" + " and (JQNeiRong like '%" + "布防" + "%'" + " or JQNeiRong like '%" + "撤防" + "%')";
        }
        initRecycler();

    }

    private void initTopbar() {
        topbar.setTitle("记录查询");
        topbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        btnShow = topbar.addRightTextButton("搜索", QMUIViewHelper.generateViewId());
        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isShowingSearch){
                    btnShow.setText("搜索");
                    dismissSearchView();
                }else {
                    btnShow.setText("收起");
                    showSearchView();
                }

            }
        });
    }

    private void showSearchView() {
        isShowingSearch=true;
        viewWrapper = new ViewWrapper(llSearch);
        ObjectAnimator.ofInt(viewWrapper, "height", DensityUtils.dip2px(AlarmRecordActivity.this, 56)).setDuration(300).start();

        KeyBoardUtils.openKeybord(etKey,AlarmRecordActivity.this);
    }
    private void dismissSearchView() {
        isShowingSearch=false;
        if (viewWrapper==null){
            return;
        }
        ObjectAnimator.ofInt(viewWrapper, "height", DensityUtils.dip2px(AlarmRecordActivity.this, 0)).setDuration(300).start();

        KeyBoardUtils.closeKeybord(etKey,AlarmRecordActivity.this);
    }
    public void setBtnVisible(int visible){
        btnShow.setVisibility(visible);
    }



    private void initRecycler() {
        mDataAdapter = new DataAdapter(this);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);

        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.default_divider_height)
                .setPadding(R.dimen.default_divider_padding)
                .setColorResource(R.color.split)
                .build();

        //mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(divider);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {

                refreshAll();

            }
        });
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (!end) {
                    // loading more
//                    queryAlarmList();

                    getAlarmList(getTableName(), field, param_filter, "15", String.valueOf(mCurrentCounter), "id", "desc");
                } else {
                    //the end
                    mRecyclerView.setNoMore(true);

                }
            }
        });
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                dismissSearchView();
                btnShow.setText("搜索");
                Bundle bundle = new Bundle();
                bundle.putSerializable(Parameters.ALARM_BEAN, mDataAdapter.getDataList().get(position));
                AlarmDetailFragment detailFragment = new AlarmDetailFragment();
                detailFragment.setArguments(bundle);
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content, detailFragment).addToBackStack("detailFragment").commit();

            }
        });
        //设置头部加载颜色
        mRecyclerView.setHeaderViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        //设置底部加载颜色
        mRecyclerView.setFooterViewColor(R.color.colorAccent, R.color.dark, android.R.color.white);
        //设置底部加载文字提示
        mRecyclerView.setFooterViewHint("拼命加载中", "已经全部为你呈现了", "网络不给力啊，点击再试一次吧");

        mRecyclerView.refresh();
    }

    /**
     * 按param_filter条件重新加载
     */
    private void refreshAll() {
        mDataAdapter.clear();
        mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
        mCurrentCounter = 1;
        end = false;
        isLogHis = false;
//                queryAlarmList();
        getAlarmList(getTableName(), field, param_filter, "15", String.valueOf(mCurrentCounter), "id", "desc");
    }


    private void addItems(ArrayList<AlarmTable> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter++;

    }

    /**
     * 查询报警记录列表
     */
    public void getAlarmList(String table, String field2, String param, String pquan, String pcurr, String kname, String ksoft) {
        String[] keys = {"table", "field", "param", "pquan", "pcurr", "kname", "ksort"};
        String[] values = {table, field2, param, pquan, pcurr, kname, ksoft};
        String[] url_keys = {"cmd", "usr", "ssn"};
        String[] url_values = {"select", BaseApplication.usrID, BaseApplication.ssn};
        String url = BaseApplication.baseUrl + NetUtil.getUrl(url_keys, url_values);
        String tojson = NetUtil.toJSON(keys, values);
        OkGo.<String>post(url)
                .upString(tojson)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().toString());
                            String ret = jsonObject.getString("ret");
                            if (ret.equals("OK")) {
                                String objStr = jsonObject.getString("obj");
                                if (objStr.equals("[]")) {
                                    if (isLogHis) {
                                        end = true;
                                    } else {
                                        isLogHis = true;
                                        if (mCurrentCounter == 1) {
                                            getAlarmList(getTableName(), field, param_filter, "15", String.valueOf(mCurrentCounter), "id", "desc");

                                        }
                                        mCurrentCounter = 0;
                                    }
                                    mRecyclerView.refreshComplete(0);
                                    return;
                                }
                                Gson gson = new Gson();
                                ArrayList<AlarmTable> list = gson.fromJson(objStr, new TypeToken<ArrayList<AlarmTable>>() {
                                }.getType());
                                if (list.size() < 15) {
                                    if (isLogHis) {
                                        end = true;
                                    } else {
                                        isLogHis = true;

                                        if (mCurrentCounter == 1) {
                                            getAlarmList(getTableName(), field, param_filter, "15", String.valueOf(mCurrentCounter), "id", "desc");

                                        }

                                        mCurrentCounter = 0;
                                    }
                                    KLog.d("shurun", end ? "结尾" : "没有结尾");

                                }

                                addItems(list);
                                mRecyclerView.refreshComplete(list.size());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }

    public String getTableName() {
        tableName = isLogHis ? "yuyinalarmlogs_ls" : "yuyinalarmlogs";
        return tableName;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        alarmList.clear();
    }


    @OnClick({R.id.tv_start, R.id.tv_end, R.id.iv_search})
    public void onViewClicked(View view) {
        KeyBoardUtils.closeKeybord(etKey,AlarmRecordActivity.this);
        switch (view.getId()) {

            case R.id.tv_start:
                TimePickerView startTimeView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        tvStart.setText(TimeUtil.Date2String(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                startTimeView.show();
                break;
            case R.id.tv_end:
                TimePickerView endTimeView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        tvEnd.setText(TimeUtil.Date2String(date));
                    }
                }).setType(new boolean[]{true, true, true, false, false, false})
                        .build();
                endTimeView.show();
                break;
            case R.id.iv_search:
                String keyWord = etKey.getText().toString().trim();
                String start_value = tvStart.getText().toString().trim();
                String end_value = tvEnd.getText().toString().trim();
                search(keyWord, start_value, end_value);
                break;
            default:
        }
    }

    private void search(String keyWord, String start_value, String end_value) {
        if (isShowingDefence) {

            param_filter = "custid='" + BaseApplication.usrID + "'" + " and " + "JQNeiRong" + " like '%" + keyWord + "%'" + " and " + "DateOn" + ">='" + start_value + "' and " + "DateOn" + "<='" + end_value + "'";


        } else {
            if (CommonUtil.isNull(keyWord)) {
                param_filter = "custid='" + BaseApplication.usrID + "'" + " and " + "DateOn" + ">='" + start_value + "' and " + "DateOn" + "<='" + end_value + "'" + " and JQNeiRong not like '%" + "布防" + "%'" + " and JQNeiRong not like '%" + "撤防" + "%'";
            } else {
                param_filter = "custid='" + BaseApplication.usrID + "'" + " and " + "JQNeiRong" + " like '%" + keyWord + "%'" + " and " + "DateOn" + ">='" + start_value + "' and " + "DateOn" + "<='" + end_value + "'" + " and JQNeiRong not like '%" + "布防" + "%'" + " and JQNeiRong not like '%" + "撤防" + "%'";
            }

        }
        btnShow.setText("搜索");
        dismissSearchView();
        refreshAll();

    }
}
